<template>
  <el-container class="page-container">
    <el-aside width="220px">
      <!-- 角色列表 -->
      <el-menu v-if="roleList.length > 0" :default-active="'' + roleList[0].roleId" @select="onSelectRole">
        <el-menu-item v-for="item in roleList" :key="item.roleId" :index="'' + item.roleId">
          <i class="el-icon-menu" />
          <template #title>
            <span>{{ item.roleName }}</span>
          </template>
          <!-- 操作角色的下拉菜单 -->
          <el-dropdown trigger="click" placement="bottom">
            <span>
              <svg-icon icon-class="more" class="more-icon" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- 编辑角色 -->
              <el-dropdown-item>
                <el-button v-auth-btn="'sys:role:add_edit'" type="text" style="color: #333" @click="$router.push(`/sys/role/editor?mode=edit&roleId=${item.roleId}`)">编辑角色</el-button>
              </el-dropdown-item>
              <!-- 删除角色 -->
              <el-dropdown-item>
                <el-button v-auth-btn="'sys:role:remove'" type="text" style="color: #ff4400" @click="onDeleteRole(item.roleId)">删除</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
        <!-- 添加角色按钮 -->
        <el-button v-auth-btn="'sys:role:add_edit'" plain type="primary" size="medium" class="add-role-btn" @click="$router.push('/sys/role/editor?mode=add')">添加角色</el-button>
      </el-menu>
    </el-aside>
    <el-main>
      <!-- 标签页 -->
      <el-tabs v-model="activeName">
        <!-- 功能权限页 -->
        <el-tab-pane label="功能权限" name="permission">
          <div class="permission-container">
            <div v-for="(item, index) in permissionTree" :key="item.id" class="permission-item">
              <!-- 标题 -->
              <div class="permission-title">{{ item.title }}</div>
              <!-- 功能权限树 -->
              <el-tree
                :ref="`permissionTreeRef${index}`"
                :data="item.children"
                show-checkbox
                node-key="id"
                :props="{ label: 'title' }"
                default-expand-all
              />
            </div>
          </div>
        </el-tab-pane>
        <!-- 成员页 -->
        <el-tab-pane :label="`成员（${ userTotal }）`" name="member">
          <el-table :data="userList" size="medium" :header-cell-style="{ background: '#f7f8f9' }">
            <el-table-column type="index" label="序号" align="center" />
            <el-table-column prop="name" label="员工姓名" align="center" />
            <el-table-column prop="userName" label="登录账号" align="center" />
          </el-table>
          <el-pagination
            :current-page.sync="userParams.page"
            layout="->, total,
             prev, pager, next"
            :total="userTotal"
            @current-change="getUserList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
</template>

<script>
import { getRoleListAPI, getPermissionTreeAPI, getRoleDetailsAPI, getRoleUsersAPI, deleteRoleAPI } from '@/api/system/role'

import { addDisabledToTree } from '@/utils/tools'

export default {
  name: 'Role',
  data() {
    return {
      roleList: [], // 角色列表
      permissionTree: [], // 功能权限树形数据
      activeName: 'permission', // 激活的标签页，默认功能权限页
      roleDetails: {
      }, // 角色详情
      userParams: {
        page: 1,
        pageSize: 10
      },
      userList: [], // 用户列表
      userTotal: 0
    }
  },
  async created() {
    this.getRoleList()
    this.getPermissionTree()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      this.roleList = await getRoleListAPI()
      // 获取第一个角色的详情（默认显示）
      this.getRoleDetails(this.roleList[0].roleId)
      // 查询角色关联的用户列表
      this.getUserList(this.roleList[0].roleId, this.userParams)
    },
    // 获取所有功能权限
    async getPermissionTree() {
      const res = await getPermissionTreeAPI()
      // 为树添加disabled属性
      this.permissionTree = addDisabledToTree(res)
    },
    // 查询当前角色详情
    async getRoleDetails(roleId) {
      // 获取角色详情
      this.roleDetails = await getRoleDetailsAPI(roleId)
      // 设置功能权限选中状态
      this.$nextTick(() => {
        this.roleDetails.perms.forEach((item, index) => {
          if (this.$refs[`permissionTreeRef${index}`] && this.$refs[`permissionTreeRef${index}`][0]) {
            this.$refs[`permissionTreeRef${index}`][0].setCheckedKeys(item)
          }
        })
      })
    },
    // 查询角色关联的用户列表
    async getUserList(roleId, params) {
      const res = await getRoleUsersAPI(roleId, params)
      this.userList = res.rows
      this.userTotal = res.total
    },
    // 选择角色
    onSelectRole(roleId) {
      this.getRoleDetails(roleId)
      this.getUserList(roleId, this.userParams)
    },
    // 删除角色
    async onDeleteRole(roleId) {
      this.$confirm('您确定删除该角色吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRoleAPI(roleId)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 重新获取角色列表
        this.getRoleList()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .el-aside {
    .el-menu {
      .el-menu-item {
        position: relative;
        .el-dropdown {
          position: absolute;
          right: 25px;
          font-size: 20px;
        }
      }
      height: 100%;
    }
    .add-role-btn {
      width: calc(100% - 50px);
      margin: 10px 30px 0 20px;
    }
  }
  .el-main {
    width: 100%;
    padding: 0;
    .el-tabs {
      ::v-deep .el-tabs__nav {
        margin-left: 20px;
      }
      .permission-container {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        .permission-item {
          padding: 0 20px;
          min-width: 0;
          border-left: 1px solid #eee;
          .permission-title {
            width: 100%;
            padding: 10px 0;
            text-align: center;
            font-size: 14px;
            background-color: #f6f7f8;
          }
          ::v-deep .el-tree {
            .el-tree-node {
              white-space: normal;
              .el-tree-node__content {
                height: auto;
                margin-top: 10px;
                line-height: 24px;
                align-items: baseline;
                .el-checkbox__inner {
                  border-color: #bbb;
                  background-color: #eee;
                }
                .el-checkbox__inner::after {
                  border-color: #777;
                }
                .el-tree-node__label {
                  color: #aaa;
                }
              }
            }
          }
        }
        .permission-item:first-child {
            border: none;
          }
      }
      .el-table {
        margin: 20px;
      }
    }
  }
}
</style>
